package httpserver

import (
	"encoding/json"
	"net/http"
)

type IHttpResponse interface {
	SetCode(code int64)
	SetMsg(msg string)
	SetData(data interface{})
	SetRequestId(string)

	GetCode() int64
	GetMsg() string
	GetData() interface{}
	GetRequestId() string

	Response(...interface{})
}

type HttpResponseData struct {
	Code      int64       `json:"code"`
	Data      interface{} `json:"data"`
	Msg       string      `json:"message"`
	RequestId string      `json:"requestId"`
}

func (d *HttpResponseData) Encode() []byte {
	s, err := json.Marshal(d)
	if err != nil {
		return []byte("response marshal err " + err.Error())
	}
	return s
}

type HttpResponse struct {
	writer   http.ResponseWriter
	respData *HttpResponseData
}

func NewHttpResponse(writer http.ResponseWriter) IHttpResponse {
	return &HttpResponse{
		writer: writer,
		respData: &HttpResponseData{
			RequestId: "",
		},
	}
}

func (resp *HttpResponse) GetCode() int64 {
	return resp.respData.Code
}

func (resp *HttpResponse) GetMsg() string {
	return resp.respData.Msg
}

func (resp *HttpResponse) GetData() interface{} {
	return resp.respData.Data
}

func (resp *HttpResponse) GetRequestId() string {
	return resp.respData.RequestId
}

func (resp *HttpResponse) SetCode(code int64) {
	resp.respData.Code = code
}

func (resp *HttpResponse) SetMsg(msg string) {
	resp.respData.Msg = msg
}

func (resp *HttpResponse) SetData(data interface{}) {
	resp.respData.Data = data
}

func (resp *HttpResponse) SetRequestId(requestId string) {
	resp.respData.RequestId = requestId
}

func (resp *HttpResponse) Response(params ...interface{}) {
	resp.writer.Write(resp.respData.Encode())
}
